package cn.controller;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.common.ConfigOption;
import cn.kpi.common.Excel.domain.SubheadModel;
import cn.kpi.common.Excel.export.ExportConfigFactory;
import cn.kpi.common.Excel.export.FileExportor;
import cn.kpi.common.Excel.export.domain.common.ExportConfig;
import cn.kpi.common.Excel.export.domain.common.ExportResult;
import cn.kpi.common.Excel.importfile.FileImportExecutor;
import cn.kpi.common.Excel.importfile.domain.common.Configuration;
import cn.kpi.common.Excel.importfile.domain.common.ImportResult;
import cn.kpi.common.Excel.importfile.impl.XmlConfigParser;
import cn.kpi.entity.attendance.AttSummaryEntity;
import cn.kpi.entity.attendance.AttTbBatchEntity;
import cn.kpi.service.attendance.IAttBmHzService;
import cn.kpi.service.attendance.IAttTbService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mysql.fabric.xmlrpc.base.Data;

import cn.common.ExceResult;
import cn.common.LayTable;
import cn.filter.LoginCheck;
import cn.kpi.common.utils.ChineseCharToPingYinUtils;
import cn.kpi.entity.sys.GeneralCodeEntity;
import cn.kpi.entity.sys.OrgEntity;
import cn.kpi.entity.sys.RoleEntity;
import cn.kpi.entity.sys.UserEntity;
import cn.kpi.service.sys.IGeneralCodeService;
import cn.kpi.service.sys.IOrgService;
import cn.kpi.service.sys.IRoleService;
import cn.kpi.service.sys.IUserService;
import org.springframework.web.multipart.MultipartFile;


import java.io.*;
import java.lang.reflect.Field;

import static cn.kpi.common.utils.DateUtils.getDay;
import static cn.kpi.common.utils.DateUtils.getMonth;
import static cn.kpi.common.utils.DateUtils.getYear;

@Controller
@RequestMapping("user")
public class UserController extends BaseController {

    @Autowired
    private IGeneralCodeService iGeneralCodeService;

    @Autowired
    private IOrgService iOrgService;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IRoleService iRoleService;
    @Autowired
    private IAttTbService iAttTbService;

    @Autowired
    private IAttBmHzService iAttBmHzService;

    @RequestMapping(value = "/user_list")
    public String UserList(Model model) {
        try {
            String where = " AND parentcode='zzmm'";
            List<GeneralCodeEntity> zzmmlst = iGeneralCodeService.GetGeneralCodeListByWhere(where);
            model.addAttribute("zzmmlst", zzmmlst);

            //List<OrgEntity> orglst = iOrgService.GetOrgList();
            //String whereOrg=" AND orgid IN ("+this.GetLoginUserOrgidsForOrg()+")";
            String whereOrg = " AND orgtype=0 ";
            whereOrg += " AND orgid IN(" + this.GetOrgListByRole() + ") ";
            List<OrgEntity> orglst = iOrgService.GetOrgListByWhere(whereOrg);
            for (int i = 0; i < orglst.size(); i++) {
                String html = "";
                for (int j = 0; j < orglst.get(i).getLevel(); j++) {
                    html += "&#12288;";
                }
                orglst.get(i).setOrgname(html + orglst.get(i).getOrgname());
            }
            model.addAttribute("orglst", orglst);

            model.addAttribute("loginuserid", this.GetLoginUserId());

            model.addAttribute("usertype", this.GetLoginUser().getUsertype());

        } catch (Exception ex) {

        }
        return "sys/user_list";
    }

    @RequestMapping(value = "/user_query")
    public String UserQuery(Model model) {
        try {
            String where = " AND parentcode='zzmm'";
            List<GeneralCodeEntity> zzmmlst = iGeneralCodeService.GetGeneralCodeListByWhere(where);
            model.addAttribute("zzmmlst", zzmmlst);

            //List<OrgEntity> orglst = iOrgService.GetOrgList();
            //String whereOrg=" AND orgid IN ("+this.GetLoginUserOrgidsForOrg()+")";
            String whereOrg = " AND orgtype=0 ";
            whereOrg += " AND orgid IN(" + this.GetOrgListByRole() + ") ";
            List<OrgEntity> orglst = iOrgService.GetOrgListByWhere(whereOrg);
            for (int i = 0; i < orglst.size(); i++) {
                String html = "";
                for (int j = 0; j < orglst.get(i).getLevel(); j++) {
                    html += "&#12288;";
                }
                orglst.get(i).setOrgname(html + orglst.get(i).getOrgname());
            }
            model.addAttribute("orglst", orglst);

            model.addAttribute("loginuserid", this.GetLoginUserId());

            model.addAttribute("usertype", this.GetLoginUser().getUsertype());

        } catch (Exception ex) {

        }
        return "sys/user_query";
    }

    @RequestMapping(value = "/user_detail")
    public String UserDetail(Model model, Long userid) {
        try {
            UserEntity entity = iUserService.GetUserById(userid);
            model.addAttribute("entity", entity);
        } catch (Exception ex) {

        }
        return "sys/user_detail";
    }

    @RequestMapping(value = "/user_edit")
    public String UserEdit(Model model, Long userid) {

        try {
            String where = " AND parentcode IN ('mz','zzmm','xl','xw','usergw','yhzt')";
            List<GeneralCodeEntity> lst = iGeneralCodeService.GetGeneralCodeListByWhere(where);
            List<GeneralCodeEntity> mzlst = new ArrayList<GeneralCodeEntity>();
            List<GeneralCodeEntity> zzmmlst = new ArrayList<GeneralCodeEntity>();
            List<GeneralCodeEntity> xllst = new ArrayList<GeneralCodeEntity>();
            List<GeneralCodeEntity> xwlst = new ArrayList<GeneralCodeEntity>();
            List<GeneralCodeEntity> usergw = new ArrayList<GeneralCodeEntity>();
            List<GeneralCodeEntity> yhzt = new ArrayList<>();
            List<GeneralCodeEntity> rank = new ArrayList<>();
            GeneralCodeEntity item = new GeneralCodeEntity();
            item.setCodedes("1");
            item.setCodename("处级领导干部");
            rank.add(item);
            GeneralCodeEntity item1 = new GeneralCodeEntity();
            item1.setCodename("科级领导干部");
            item1.setCodedes("2");
            rank.add(item1);
            GeneralCodeEntity item2 = new GeneralCodeEntity();
            item2.setCodename("民警");
            item2.setCodedes("3");
            rank.add(item2);
            GeneralCodeEntity item3 = new GeneralCodeEntity();
            item3.setCodename("未定职务(新录用公务员)");
            item3.setCodedes("4");
            rank.add(item3);
            GeneralCodeEntity item4 = new GeneralCodeEntity();
            item4.setCodename("领导班子");
            item4.setCodedes("5");
            rank.add(item4);


            for (int i = 0; i < lst.size(); i++) {
                if (lst.get(i).getParentcode().equals("mz")) {
                    mzlst.add(lst.get(i));
                } else if (lst.get(i).getParentcode().equals("zzmm")) {
                    zzmmlst.add(lst.get(i));
                } else if (lst.get(i).getParentcode().equals("xl")) {
                    xllst.add(lst.get(i));
                } else if (lst.get(i).getParentcode().equals("xw")) {
                    xwlst.add(lst.get(i));
                } else if (lst.get(i).getParentcode().equals("usergw")) {
                    usergw.add(lst.get(i));
                } else if (lst.get(i).getParentcode().equals("yhzt")) {
                    yhzt.add(lst.get(i));
                }
            }

            model.addAttribute("mzlst", mzlst);
            model.addAttribute("zzmmlst", zzmmlst);
            model.addAttribute("xllst", xllst);
            model.addAttribute("xwlst", xwlst);
            model.addAttribute("usergw", usergw);
            model.addAttribute("yhzt", yhzt);
            model.addAttribute("rank", rank);

            String whereOrg = "";
            List<OrgEntity> orglstgroup = iOrgService.GetOrgListByWhere(whereOrg);
            List<OrgEntity> orglst = new ArrayList<OrgEntity>();
            for (int i = 0; i < orglstgroup.size(); i++) {
                if (orglstgroup.get(i).getOrgtype() == 0) {
                    orglst.add(orglstgroup.get(i));
                }
            }
            model.addAttribute("orglstgroup", orglstgroup);
            model.addAttribute("orglst", orglst);


            if (userid > 0) {
                UserEntity entity = iUserService.GetUserById(userid);
                model.addAttribute("entity", entity);
            }

            List<RoleEntity> lstrole = iRoleService.GetRoleList(" 1=1 ");
            model.addAttribute("lstrole", lstrole);
        } catch (Exception ex) {

        }
        return "sys/user_edit";
    }

    public boolean changeUserOrg(Long userid, Long szdw) {

        try {

            Integer iResult = 0;

            //1.取出待添加部门的状态
            List<AttTbBatchEntity> attTbBatchEntities = iAttTbService.GetOrgSummaryList(szdw, "att");


            if (attTbBatchEntities.size() > 0) {
                Calendar calendar = Calendar.getInstance();
                int y = calendar.get(Calendar.YEAR);
                int m = calendar.get(Calendar.MONTH) + 1;
                int d = calendar.get(Calendar.DAY_OF_MONTH);
                if (d < 20) {
                    if (m == 1) {
                        m = 12;
                        y = y - 1;
                    } else m = m - 1;
                }
//
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                calendar.setTime(sdf.parse(y + "-" + m + "-1"));
//                int countday = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

                int qqtsset = iAttBmHzService.GetQqDaysByYearAndMonth(y, m);
                if (qqtsset <= 0) {
//                    result.setCode(300);
//                    result.setResult(iResult);
//                    result.setMsg("未配置本月出勤天数");
                    return false;
                }


                //2.部门已归档，部门未生成，都不做任何处理
                //取出部门非归档状态的orgsummaryid
                AttTbBatchEntity inEntity = attTbBatchEntities.get(0);

                //取出用户信息，部门修改人员为生成人员
                UserEntity byUser = this.GetLoginUser();
                inEntity.setUserid(userid);//修改人
                inEntity.setOrgid(szdw);//修改人部门
                inEntity.setByuserszdw(byUser.getSzdw());
                inEntity.setByuserszdwname(byUser.getOrgname());
                inEntity.setByuseruserstatus(byUser.getUserstatus());
                inEntity.setByuserrsgxszdw(byUser.getRsgxszdw());
                inEntity.setByuserrsgxszdwname(byUser.getRsgxorgname());
                inEntity.setDays(qqtsset);//设置出勤天数

                //3.新部门是否已经有了该用户
                String strWhere = "";
                strWhere += " AND year=" + y;
                strWhere += " AND mouth=" + m;
                strWhere += " AND userid=" + userid;
                strWhere += " AND szdw = " + szdw;
                List<AttSummaryEntity> newList = iAttTbService.GetAttTbListByWhere(strWhere);


                //4.创建一条新的数据
                if (newList.size() == 0)
                    iResult = iAttTbService.CreateInsertAttTbByUserid(inEntity);

                if (iResult > 0) {
                    return true;
                } else {
                    return false;
                }

            } else {
                return false;
            }
        } catch (Exception ex) {
            return false;
        }

    }


    @RequestMapping(value = "/add_user")
    public String AddUser(HttpServletRequest request, HttpServletResponse response) {
        try {

            UserEntity entity = new UserEntity();
            if (request.getParameter("username") != null) {
                entity.setUsername(request.getParameter("username").trim());
            }
            entity.setUserpwd("123456");
            if (request.getParameter("realname") != null) {
                entity.setRealname(request.getParameter("realname").trim());
            }
            entity.setIsdelete(0);
            if (request.getParameter("phone") != null) {
                entity.setPhone(request.getParameter("phone").trim());
            }
            if (request.getParameter("nation") != null) {
                entity.setNation(request.getParameter("nation").trim());
            }
            entity.setSex(Integer.parseInt(request.getParameter("sex")));
            if (request.getParameter("userjg") != null) {
                entity.setUserjg(request.getParameter("userjg").trim());
            }

            entity.setBirthplace(request.getParameter("birthplace").trim());
            entity.setDomicileplace(request.getParameter("domicileplace").trim());
            entity.setBirthday(Date.valueOf(request.getParameter("birthday").trim()));
            if (request.getParameter("joinpartytime") != null && !request.getParameter("joinpartytime").equals("")) {
                entity.setJoinpartytime(Date.valueOf(request.getParameter("joinpartytime")));
            }
            entity.setRank(request.getParameter("rank"));
            entity.setUserno(request.getParameter("userno").trim());
            entity.setZzmm(request.getParameter("zzmm").trim());
            entity.setSzdw(Long.valueOf(request.getParameter("szdw").trim()));
            entity.setUserno(request.getParameter("userno").trim());
            entity.setCjgagzsj(Date.valueOf(request.getParameter("cjgagzsj").trim()));
            entity.setCjgzsj(Date.valueOf(request.getParameter("cjgzsj").trim()));
            entity.setQualifications(request.getParameter("qualifications").trim());
            entity.setDegree(request.getParameter("degree").trim());
            entity.setByuserid(this.GetLoginUserId());
            entity.setRemark("");
            entity.setCardno(request.getParameter("cardno").trim());

            entity.setStatus(0);
            entity.setHomeurl(request.getParameter("homeurl"));
            entity.setUsergw(request.getParameter("usergw"));
            entity.setUsertype(Integer.parseInt(request.getParameter("usertype")));

            ChineseCharToPingYinUtils pinyin = new ChineseCharToPingYinUtils();
            entity.setKeyword(pinyin.getAllFirstLetter(entity.getRealname()));

            String groupid = request.getParameter("groupid");
            if (groupid != null && groupid.length() > 0) {
                entity.setGroupid(Long.valueOf(groupid));
            }
            entity.setRoleid(Long.valueOf(request.getParameter("roleid").trim()));

            Calendar from = Calendar.getInstance();
            from.setTime(entity.getBirthday());
            Calendar to = Calendar.getInstance();
            java.util.Date now = new java.util.Date();
            to.setTime(now);

            int fromYear = from.get(Calendar.YEAR);
            int toYear = to.get(Calendar.YEAR);

            entity.setAge(toYear - fromYear);

            String sUserid = request.getParameter("userid");
            if (sUserid != null && sUserid.length() > 0) {
                Long userid = Long.parseLong(sUserid);
                if (userid > 0) {
                    entity.setUserid(userid);
                }
            }

            entity.setRsgxszdw(Long.valueOf(request.getParameter("rsgxszdw").trim()));
            entity.setGrsf(request.getParameter("grsf").trim());
            entity.setLdzw(request.getParameter("ldzw").trim());
            entity.setFldzw(request.getParameter("fldzw").trim());
            entity.setCsgz(request.getParameter("csgz").trim());
            entity.setJxxx(request.getParameter("jxxx").trim());
            entity.setZzjyxl(request.getParameter("zzjyxl").trim());
            entity.setZzjyxw(request.getParameter("zzjyxw").trim());
            entity.setUserstatus(request.getParameter("useryhzt").trim());//补用户状态
            int rs = 0;
            int iResult = 0;
            if (entity.getUserid() > 0) {
                rs = updateKH(entity.getUserid(), entity.getSzdw(), entity.getRsgxszdw());
                iResult = iUserService.UpdateEntity(entity);
            } else {
                if (iUserService.GetUserListCountByWhere(" AND username='" + entity.getUsername() + "'") > 0) {
                    return renderStringScript(response, "<script>window.parent.CloseDialog(0,'已存在相同用户名')</script>");
                }
                iResult = iUserService.InsertEntity(entity);
            }


            return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + "," + rs + ")</script>");
        } catch (Exception ex) {
            ex.printStackTrace();
            return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
        }
    }


    /*
    dw:新单位
    rsdw：新单位
     */
    private int updateKH(Long userId, Long dw, Long rsdw) {
//用户所在

        try {
            int y, m, d;
            Calendar cal = Calendar.getInstance();
            y = cal.get(Calendar.YEAR);
            m = cal.get(Calendar.MONTH) + 1;
            d = cal.get(Calendar.DAY_OF_MONTH);
            UserEntity userEntity = iUserService.GetUserById(userId);

            //月度逻辑处理，每月20号后取当月，每月20号前取上月
            if (d < 20) {
                if (m == 1) {
                    m = 12;
                    y = y - 1;
                } else m = m - 1;
            }

            String strWhere = "";
            String updateSql = "";
            strWhere += " AND year=" + y;
            strWhere += " AND mouth=" + m;

            String oldWhere = strWhere;
            String newWhere = strWhere;
            //oldWhere += " AND szdw = " + userEntity.getSzdw();//为适应excle导入，去掉部门判断，是否有旧的通过是否有数据就可以确定
            oldWhere += " AND userid=" + userId;
            newWhere += " AND szdw = " + dw;
            List<AttSummaryEntity> oldList = iAttTbService.GetAttTbListByWhere(oldWhere);
            List<AttSummaryEntity> newList = iAttTbService.GetAttTbListByWhere(newWhere);

            //已经归档，不处理
            if (newList.size() > 0) {
                if (newList.get(0).getStatus() == 2) {
                    return 0;
                }
            }
            if (oldList.size() > 0) {
                long oldszdw = oldList.get(0).getSzdw();
                //已经归档不处理
                if (oldList.get(0).getStatus() == 2) return 0;
                //新旧都有
                if (newList.size() > 0 && oldszdw != dw) {
                    updateSql += ",szdw=" + dw;
                    updateSql += ",rsgxszdw=" + rsdw;
                    updateSql += ",szdwname='" + iOrgService.GetOrgById(dw).getOrgname() + "'";
                    updateSql += ",rsgxszdwname='" + iOrgService.GetOrgById(rsdw).getOrgname() + "'";
                    updateSql += " where attsummaryid=" + oldList.get(0).getAttsummaryid();
                    iAttTbService.UpdateAttKH(newList.get(0).getOrgsummaryid(), dw, rsdw, iOrgService.GetOrgById(dw).getOrgname(), iOrgService.GetOrgById(rsdw).getOrgname(), oldList.get(0).getAttsummaryid());
                    iAttBmHzService.UpdateAttStatus(oldList.get(0).getOrgsummaryid(), 0);
                    iAttBmHzService.UpdateAttStatus(newList.get(0).getOrgsummaryid(), 0);
                    return 1;
//                } else if (userEntity.getRsgxszdw() != rsdw) {
//                    //新无旧有
//                    updateSql = "";ng + iOrgService.GetOrgById(rsdw).getOrgname() + "'";
//                    updateSql += " where attsummaryid=" + oldList.get(0).getAttsummaryid();
//                    iAttBmHzService.UpdateAttStatus(oldList.get(0).getOrgsummaryid(), 0);
//                    iAttTbService.UpdateAttKH(oldList.get(0).getOrgsummaryid(), dw, rsdw, iOrgService.GetOrgById(dw).getOrgname(), iOrgService.GetOrgById(rsdw).getOrgname(), oldList.get(0).getAttsummaryid());
//                    return 1;

                } else if (newList.size() <= 0 && oldszdw != dw) {//excle导入处理
                    iAttBmHzService.UpdateAttStatus(oldList.get(0).getOrgsummaryid(), 0);
                    iAttTbService.DeleteKQ(oldList.get(0).getAttsummaryid());
                    return 1;
                }


            } else {
                //新有，旧无
                if (newList.size() > 0) {
                    Boolean rs = this.changeUserOrg(userEntity.getUserid(), dw);
                    if (rs) return 1;
                    return 0;
                }
                return 0;


            }
            return 0;

        } catch (Exception ex) {


            return 0;
        }
    }


    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_list")
    public LayTable<UserEntity> GetList(HttpServletRequest request) {

        List<UserEntity> lst = null;
        LayTable<UserEntity> layTable = new LayTable<UserEntity>();
        try {
            String realname = request.getParameter("realname");
            String userno = request.getParameter("userno");
            String zzmm = request.getParameter("zzmm");
            String szdw = request.getParameter("szdw");
            String where = "";
            if (realname != null && realname.length() > 0) {
                where += " AND realname LIKE '%" + realname + "%'";
            }
            if (userno != null && userno.length() > 0) {
                where += " AND userno LIKE '%" + userno + "%'";
            }
            if (zzmm != null && zzmm.length() > 0) {
                where += " AND zzmm='" + zzmm + "'";
            }
            where += " AND  ISNULL(isdelete)=1 ";
            if (szdw != null && szdw.length() > 0 && !szdw.equals("0")) {
                OrgEntity orgentity = iOrgService.GetOrgById(Long.parseLong(szdw));
                where += " AND szdw IN (SELECT orgid FROM t_sys_org WHERE lft>=" + orgentity.getLft() + " AND lft<=" + orgentity.getRgt() + ")";
            }


            where += this.GetUserListByRole();

            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            int beginrow = (page - 1) * limit;
            int endrow = limit;


            lst = iUserService.GetUserListLimitByWhere(where, beginrow, endrow);
            for (int i = 0; i < lst.size(); i++) {
                lst.get(i).setRowNum(i + 1);
            }

            int iCount = iUserService.GetUserListCountByWhere(where);
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(lst);

        } catch (Exception e) {
            layTable.setCode(500);
        }
        return layTable;
    }

    @ResponseBody
    @RequestMapping(value = "/delete_user")
    public ExceResult DeleteUser(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            Long userid = Long.parseLong(request.getParameter("userid"));
            int iResult = iUserService.DeleteEntity(userid);
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }

    //todo:需要加入导入功能
    @ResponseBody
    @RequestMapping(value = "/export")
    public ExceResult export(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        try {


            String realname = request.getParameter("realname");
            String userno = request.getParameter("userno");
            String zzmm = request.getParameter("zzmm");
            String szdw = request.getParameter("szdw");
            String where = "AND (isdelete is NULL or isdelete !=1)";
            if (realname != null && realname.length() > 0) {
                where += " AND realname LIKE '%" + realname + "%'";
            }
            if (userno != null && userno.length() > 0) {
                where += " AND userno LIKE '%" + userno + "%'";
            }
            if (zzmm != null && zzmm.length() > 0) {
                where += " AND zzmm='" + zzmm + "'";
            }
            if (szdw != null && szdw.length() > 0 && !szdw.equals("0")) {
                OrgEntity orgentity = iOrgService.GetOrgById(Long.parseLong(szdw));
                where += " AND szdw IN (SELECT orgid FROM t_sys_org WHERE lft>=" + orgentity.getLft() + " AND lft<=" + orgentity.getRgt() + ")";
            }


            where += this.GetUserListByRole();

            int page = 1;
            int limit = 100000;
            int beginrow = (page - 1) * limit;
            int endrow = limit;


            List<UserEntity> lst = iUserService.GetUserListLimitByWhere(where, beginrow, endrow);

            String fileName = "房山公安局人员信息表" + new Random().nextInt() + ".xlsx";
            SubheadModel subheadingVo = new SubheadModel();
            subheadingVo.setHeader("人员信息表");
            subheadingVo.setSheetName("人员信息");
            ExportConfig exportConfig = ExportConfigFactory.getConfig("user.xml");
            ExportResult exportResult = FileExportor.getExportResult(exportConfig, lst, subheadingVo);
            String saveUrl = ConfigOption.getInstance().getFileurl();//服务器缓存地址
            String saveFileUrl = ConfigOption.getInstance().getFileurl() + "/" + fileName;
            OutputStream outputStream = new FileOutputStream(saveFileUrl);
            exportResult.export(outputStream);

            String url = ConfigOption.getInstance().getWeburl() + fileName;
            result.setCode(200);
            result.setResult(1);
            result.setMsg(url);
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
            ex.printStackTrace();
        }
        return result;
    }


    @RequestMapping(value = "/user_info_upload", method = RequestMethod.POST)
    @ResponseBody
    public ExceResult excleUpload(@RequestParam("file") MultipartFile file) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        if (null != file) {
            String myFileName = file.getOriginalFilename();// 文件原名称

            String fileName = Integer.toHexString(new Random().nextInt()) + "." + myFileName.
                    substring(myFileName.lastIndexOf(".") + 1);

            String basepath = ConfigOption.getInstance().getFileurl();
            String fileRoute = getSavePath(basepath);
            File fileDir = new File(fileRoute);
            if (!fileDir.exists()) { //如果不存在 则创建
                fileDir.mkdirs();
            }
            String path = fileRoute + fileName;
            File localFile = new File(path);
            try {
                file.transferTo(localFile);
                result.setCode(200);
                result.setResult(1);
                result.setMsg(path);
            } catch (IllegalStateException e) {
                e.printStackTrace();
                result.setCode(500);
                result.setResult(0);
                result.setMsg(e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
                result.setCode(500);
                result.setResult(0);
                result.setMsg(e.getMessage());
            }
        } else {
            result.setCode(300);
            result.setResult(0);
            result.setMsg("上传文件为空！");
        }
        return result;
    }


    @ResponseBody
    @RequestMapping(value = "/add_user_info")
    public ExceResult AddVtdpUserTj(HttpServletRequest request) {
        ExceResult result = new ExceResult();
        String path = request.getParameter("path");
        try {

            int iResult = 0;
            //1.excle读取解析
            //a.获取模板
            XmlConfigParser xmlConfigParser = new XmlConfigParser();
            Configuration configuration = xmlConfigParser.getConfig("userinfo.xml");
            //b.读取路径
            File files = new File(path);
            ImportResult mapMapResult = FileImportExecutor.importFile(configuration, files, files.getName(), "UserInfo");
            List<Map<String, Object>> maps = mapMapResult.getResult();

            //2.数据加入当前用户的组织机构
            List<UserEntity> entitys = new ArrayList<>();

            //3.拼接实体类,补上导入数据
            for (Map<String, Object> map : maps) {
                UserEntity entity = new UserEntity();
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    int rownum = +entitys.size() + 5;
                    Field fd = UserEntity.class.getDeclaredField(entry.getKey());
                    fd.setAccessible(true);
                    Object value = entry.getValue().toString();
                    if (value != null && !value.equals("")) {
                        //如果是0，就是男，如果是1就是女
                        if (fd.getName().equals("sex")) {
                            if (value.equals("男")) {
                                value = 0;
                            } else if (value.equals("女")) {
                                value = 1;
                            } else {
                                result.setCode(300);
                                result.setResult(0);
                                result.setMsg("行" + rownum + "，excel男女性别错误!错误值： " + value);
                                throw new Exception("男女性别错误！");
                            }
                        }
                        if (fd.getName().contains("sj") || fd.getName().contains("time") || fd.getName().contains("day")) {
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                            value = sdf.parse(value.toString());
                        }

                        if (fd.getName().equals("rank")) {
                            if (value.toString().contains("处级领导干部")) value = "1";
                            else if (value.toString().contains("科级领导干部")) value = "2";
                            else if (value.toString().contains("民警")) value = "3";
                            else if (value.toString().contains("未定职务(新录用公务员)")) value = "4";
                            else if (value.toString().contains("领导班子")) value = "5";
                            else {
                                result.setCode(300);
                                result.setResult(0);
                                result.setMsg("行" + rownum + "，excel职级错误！错误值： " + value);
                                throw new Exception("职级错误！");
                            }
                        }

                        fd.set(entity, value);
                    }
                }
                entitys.add(entity);
            }
            //验证数据的完整性
            if (!checkDate(entitys).equals("")) {
                result.setCode(300);
                result.setResult(0);
                result.setMsg("组织机构");
                return result;
            }
            ;

            //数据拆分，那些是新增加，那些是更新
            List<UserEntity> inEntitys = new ArrayList<>();
            List<UserEntity> upEntitys = new ArrayList<>();
            for (UserEntity entity : entitys) {
                int con = 0;
                String where = " AND cardno = " + entity.getCardno();
                con = iUserService.GetUserListCountByWhere(where);
                if (con != -1) {
                    if (con == 0) {
                        inEntitys.add(entity);
                    } else {
                        upEntitys.add(entity);
                    }
                }
            }
            //插入数据
            iResult = iUserService.UpdateEntityList(inEntitys, upEntitys);


            if (iResult > 0) {
                result.setCode(200);
                result.setResult(1);
                result.setMsg("导入成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            if (result.getCode() != 300) {
                result.setCode(500);
                result.setResult(0);
                result.setMsg("操作异常");
            }
            ex.printStackTrace();
        }
        return result;
    }

    private String checkDate(List<UserEntity> entitys) throws Exception {
        String mes = "";
        //检查数据完整性
        for (UserEntity entity : entitys) {
            //1.组织机构是否有ID验证
            if (entity.getOrgname() != null && !entity.getOrgname().equals("")) {
                String orgname = entity.getOrgname();
                OrgEntity orgEntity = iOrgService.GetOrgByName(orgname);
                if (orgEntity == null) {
                    mes = "实际工作单位：" + entity.getOrgname() + "未匹配上，请检查后重新导入";
                } else {
                    entity.setSzdw(orgEntity.getOrgid());
                }
            }

            //2.实际工作组织机构
            if (entity.getRsgxorgname() != null && !entity.getRsgxorgname().equals("")) {
                String rsgxszdwname = entity.getRsgxorgname();
                OrgEntity orgEntity = iOrgService.GetOrgByName(rsgxszdwname);
                if (orgEntity == null) {
                    mes = "人事关系所在单位：" + entity.getOrgname() + "未匹配上，请检查后重新导入";
                } else {
                    entity.setRsgxszdw(orgEntity.getOrgid());
                }
            }

            //3.当前角色
            if (entity.getRolename() != null && !entity.getRolename().equals("")) {
                String rolename = entity.getRolename();
                RoleEntity roleEntity = iRoleService.GetRoleByName(rolename);
                if (roleEntity == null) {
                    mes = "rolename：" + entity.getRolename() + "未匹配上，请检查后重新导入";
                } else {
                    entity.setRoleid(roleEntity.getRoleid());
                }


            }

        }

        return mes;
    }

    //导入页面初始化
    @RequestMapping(value = "/user_list_info_import")
    public String userPayImportinit(HttpServletRequest request, Model model) {
        try {

            String year = request.getParameter("month");
            String month = request.getParameter("year");
            model.addAttribute("year", year);
            model.addAttribute("month", month);
        } catch (Exception ex) {
        }
        return "sys/user_list_info_import";
    }


    public String getSavePath(String url) {
//        todo:最好动态获取，改为动态的路径
        String savePath = url + "/" + getYear() + "/" + getMonth() + "/" + getDay() + "/";
        File dirPath = new File(savePath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        return savePath;
    }
}
